import Vue from "vue";
import VueRouter from "vue-router";
import { routes } from "./routes";
// import store from "@/store";
// import { isBlank } from "@/utils/dataType";
import { ACCESS_TOKEN } from "@/store/mutation-types";

// 路由配置
Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

const router = new VueRouter({
  // mode: "history",
  mode: "hash",
  base: process.env.BASE_URL,
  scrollBehavior(to, from, savedPosition) {
    //只有调用了history.pushState()的时候才会触发这个方法，也就是当我们点击浏览器中的“<-” "->"的时候
    //判断如果滚动条的位置存在直接返回当前位置，否则返回到起点
    //savedPosition只有当用户点击前进后退，或者go(-1)的时候才会调用
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
  routes
});

// 路由跳转拦截
router.beforeEach(async (to, from, next) => {
  // 标题替换
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  //判断目标路由是否需要登录验证
  if (to.meta.requireAuth) {
    if (Vue.ls.get(ACCESS_TOKEN)) {
      next();
    } else {
      next("/login");
    }
  } else {
    if (to.path === "/login") {
      if (Vue.ls.get(ACCESS_TOKEN)) {
        next("/");
      } else {
        next();
      }
    } else {
      next();
    }
  }
  // next();
});

export default router;
